package com.supinfo.suptracking.servlet;

import com.supinfo.suptracking.entity.Car;
import com.supinfo.suptracking.entity.Gpspositionhistory;
import com.supinfo.suptracking.service.CarService;
import com.supinfo.suptracking.service.GpsPositionHistoryService;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Fabien, Jérémy, Ludovic, Brice
 */

@WebServlet(name = "ActualiseCarServlet", urlPatterns = {"/auth/actualiseCar"})
public class ActualiseCarServlet extends HttpServlet {

    @EJB
    private CarService carServ;
    
    @EJB
    private GpsPositionHistoryService gpsServ;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get form fields
        String carIdTemp = request.getParameter("carIdActualise");
        
        // Transform id in long
        Long carId=Long.valueOf(carIdTemp);
        
        // Generation of 2 random values
        Random rand = new Random();
        int range = 1000 - 100 + 1;
        int randomLat = rand.nextInt(range) + 100;
        int randomLong = rand.nextInt(range) + 100;
        String randomLatStr = String.valueOf(randomLat);
        String randomLongStr = String.valueOf(randomLong);
        
        // Update gps datas
        Car car = carServ.processGetCarById(carId);
        String oldLat = car.getActualLatitude();
        String oldLong = car.getActualLongitude();
        car.setActualLatitude(randomLatStr);
        car.setActualLongitude(randomLongStr);
        carServ.processUpdateCar(car);
        
        // Creation of a gpshistory
        Gpspositionhistory newGpsPosHist = new Gpspositionhistory();
        newGpsPosHist.setCar(car);
        Date date=new Date(); // Actual date
        newGpsPosHist.setDate(date);
        newGpsPosHist.setLatitude(oldLat);
        newGpsPosHist.setLongitude(oldLong);
        gpsServ.processAddPositionHistory(newGpsPosHist);
        
        // Notification of user and redirection
        request.getSession().setAttribute("event", "1");
        request.getSession().setAttribute("message", "Car position actualized!");
        response.sendRedirect(getServletContext().getContextPath()+"/auth/listCar");
    }
}
